package com.open.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.open.auth.filter.JwtAuthenticationTokenFilter;
import com.open.auth.handler.AccessDeniedHandlerImpl;
import com.open.auth.service.impl.UserDetailsServiceImpl;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    
    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;
    
    @Autowired
    AccessDeniedHandlerImpl accessDeniedHandler;
    
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    
    //注入AuthenticationManager
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义认证与授权
        auth.userDetailsService(userDetailsService)
        	.passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 将 check_token 暴露出去，否则资源服务器访问时报 403 错误
        web.ignoring().antMatchers("/oauth/check_token");
    }
    
    //过滤策略
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http
//                //关闭csrf
//                .csrf().disable()
//                //不通过Session获取SecurityContext
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                .and()
//                .authorizeRequests()
//                // 对于登录接口 允许匿名访问
//                .antMatchers("/user/login").anonymous()
//                // 除上面外的所有请求全部需要鉴权认证
//                .anyRequest().authenticated()
//                .and()
//                //将jwt过滤器添加到UsernamePasswordAuthenticationFilter之前
//                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
//                //配置自定义异常处理器
//                .exceptionHandling()
//                    //认证失败处理器
//                    .authenticationEntryPoint(authenticationEntryPoint)
//                    //授权失败处理器
//                    .accessDeniedHandler(accessDeniedHandler);
    	
    	http
        .requestMatchers()
        .antMatchers("/auth/login", "/auth/authorize", "/oauth/authorize") //"/oauth/token"
        .and()
        .authorizeRequests()
        // 自定义页面或处理url是，如果不配置全局允许，浏览器会提示服务器将页面转发多次
        .antMatchers("/auth/login", "/auth/authorize")
        .permitAll()
        .anyRequest()
        .authenticated();

	    // 表单登录
	    http.formLogin()
	            // 登录页面
	            .loginPage("/auth/login")
	            // 登录处理url
	            .loginProcessingUrl("/auth/authorize");
	    http.httpBasic().disable();

    }
}